package com.peanut.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.orm.mapper.BaseService;
import com.peanut.entity.AdminUser;
import com.peanut.entity.Page;
import com.peanut.entity.dto.MyInfo;
import com.peanut.entity.dto.MyPassword;
import com.peanut.entity.vo.BookVO;
import com.peanut.mapper.AdminUserMapper;
import com.peanut.service.AdminUserService;
import com.spring.annotation.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminUserServiceImpl extends BaseService<AdminUserMapper, AdminUser> implements AdminUserService {
	
	@Override
	public AdminUser login(String name, String password) {
		
		String md5password = MD5.create().digestHex(password, "utf-8");
		AdminUser login = baseMapper.login(name, md5password);
		
		if (login != null) {
			// 登录成功，更新登录时间
			AdminUser adminUser = new AdminUser();
			adminUser.setId(login.getId());
			adminUser.setLoginTime(LocalDateTime.now());
			baseMapper.updateById(adminUser);
		}
		return login;
	}
	
	@Override
	public Page<AdminUser> pageList(Integer currentPage, Integer pageSize) {
		int total = baseMapper.count();
		int pageCount = (int) (Math.ceil((double) total / pageSize));     // 计算分页数量和当前处于第几页
		currentPage = currentPage > pageCount ? pageCount : currentPage;
		
		Page<AdminUser> listPage = new Page<>();
		listPage.setTotal(total);
		listPage.setPageCount(pageCount);
		listPage.setPageSize(pageSize);
		listPage.setCurrentPage(currentPage);
		
		if (total != 0) {
			List<AdminUser> AdminUsers = baseMapper.pageQuery((currentPage - 1) * pageSize, pageSize);
			listPage.setData(AdminUsers);
		}
		return listPage;
	}
	
	
	@Override
	public boolean deleteAdminUser(int id) {
		AdminUser user = this.getById(id);
		if (user != null) {
			user.setIsValid(0);
			if (this.update(user)) {
				return true;
			}
		}
		return false;
	}
	
	
	@Override
	public boolean updateAdminUser(AdminUser adminUser) {
		
		AdminUser user = this.getById(adminUser.getId());
		if (user != null) {
			user.setUserName(adminUser.getUserName());
			user.setIsValid(adminUser.getIsValid());   // 仅仅更新2个状态
			user.setRoleId(adminUser.getRoleId());
			
			if (this.update(user)) {
				return true;
			}
		}
		return false;
	}
	
	
	@Override
	public MyInfo queryMyInfo(int id) {
		return baseMapper.queryMyInfo(id);
	}
	
	@Override
	public boolean updateMyInfo(MyInfo myInfo, int id) {
		return baseMapper.updateMyInfo(myInfo, id) > 0;
	}
	
	@Override
	public boolean modifyMyPassword(MyPassword myPassword, int id) {
		AdminUser adminUser = baseMapper.selectById(id);
		MD5 md5 = MD5.create();
		String md5OldPassword = md5.digestHex(myPassword.getOldPassword());
		if (adminUser.getPassword().equals(md5OldPassword)) {
			String md5NewPassword = md5.digestHex(myPassword.getNewPassword(), "utf-8");
			return baseMapper.updateMyPassword(md5NewPassword, id) > 0;
		}
		return false;
	}
}
